package exilim.exf1.cspacker.worker;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.SwingWorker;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;

/**
 * 
 * @author Janos
 * @version 15.08.2010 | 17:48:43
 * 
 */
public class ScanFolderWorker extends SwingWorker<Map<Integer, Map<Integer, File>>, Integer> {

	private static final int EXIF_CASIO_TAGTYPE_SEQUENCE_NUMBER = 12545;
	private static final int EXIF_CASIO_TAGTYPE_SEQUENCE_ORDERING = 12546;

	private final File[] files;

	public ScanFolderWorker(final File[] files) {
		this.files = files;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.SwingWorker#doInBackground()
	 */
	@Override
	protected Map<Integer, Map<Integer, File>> doInBackground() throws Exception {

		setProgress(0);

		final Map<Integer, Map<Integer, File>> result = new HashMap<Integer, Map<Integer, File>>();

		if (this.files == null) {
			return result;
		}

		int progress = 0;
		final int count = this.files.length;

		for (final File file : this.files) {

			// Thread.sleep(5);

			++progress;
			final int progressPerc = (int) (((double) progress / (double) count) * 100);
			setProgress(progressPerc);

			final Metadata metadata;
			try {
				metadata = JpegMetadataReader.readMetadata(file);
			} catch (final JpegProcessingException e) {
				e.printStackTrace();
				continue;
			}

			final Directory directory = metadata.getDirectory(com.drew.metadata.exif.CasioType2MakernoteDirectory.class);
			if (directory == null) {
				// No Casio EXIF data available.
				continue;
			}

			try {
				final int serNumber = directory.getInt(EXIF_CASIO_TAGTYPE_SEQUENCE_NUMBER);
				if (serNumber == 0) {
					continue;
				}

				Map<Integer, File> sequenceFiles = result.get(serNumber);
				if (sequenceFiles == null) {
					sequenceFiles = new HashMap<Integer, File>();
					result.put(serNumber, sequenceFiles);
				}

				final int seqNumber = directory.getInt(EXIF_CASIO_TAGTYPE_SEQUENCE_ORDERING);
				sequenceFiles.put(seqNumber, file);
			} catch (final MetadataException e) {
				continue;
			}

		}

		return result;
	}

}
